package com.cangxuan.app.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.cangxuan.app.entity.User;

import java.io.File;

/**
 * 用户 工具类
 */
public class UserUtils {


    /**
     * 获取当前用户
     *
     * @param context
     * @return 当前登录的user对象，如果返回为null，说明未登录或者登录失效了
     */
    public static User getUser(Context context) {
        User user = null;
        SharedPreferences sharedPreferences = context.getSharedPreferences("userInfo", context.MODE_PRIVATE);
        if (sharedPreferences != null && sharedPreferences.contains("id") && sharedPreferences.getInt("id", 0) > 0) {
            Log.i("UserUtils", "取到用户信息了....");
            user = new User();
            user.setId(sharedPreferences.getInt("id", 0));
            user.setMobile(sharedPreferences.getString("mobile", null));
            user.setNickname(sharedPreferences.getString("nickname", null));
            user.setFace(sharedPreferences.getString("face", null));
            user.setBlockchainAddress(sharedPreferences.getString("blockchainAddress", null));
            user.setHasSetTransPassword(sharedPreferences.getBoolean("hasSetTransPassword", false));
            user.setHasSetRealname(sharedPreferences.getBoolean("hasSetRealname", false));
            user.setSubscribeToTheSalesCalendar(sharedPreferences.getBoolean("subscribeToTheSalesCalendar", false));
            user.setDisplayMyGoods(sharedPreferences.getBoolean("displayMyGoods", false));
            user.setDisplayMySellGoods(sharedPreferences.getBoolean("displayMySellGoods", false));
        }
        return user;
    }

    /**
     * 设置当前用户
     *
     * @param context
     * @param user
     */
    public static void setUser(Context context, User user) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("userInfo", context.MODE_PRIVATE);
        //获取编辑器对象
        SharedPreferences.Editor editor = sharedPreferences.edit();
        //准备数据
        editor.putInt("id", user.getId());
        editor.putString("mobile", user.getMobile());
        editor.putString("nickname", user.getNickname());
        editor.putString("face", user.getFace());
        editor.putString("blockchainAddress", user.getBlockchainAddress());
        editor.putBoolean("hasSetTransPassword", user.isHasSetTransPassword());
        editor.putBoolean("hasSetRealname", user.isHasSetRealname());
        editor.putBoolean("subscribeToTheSalesCalendar", user.isSubscribeToTheSalesCalendar());
        editor.putBoolean("displayMyGoods", user.isDisplayMyGoods());
        editor.putBoolean("displayMySellGoods", user.isDisplayMySellGoods());
        //提交数据
        editor.commit();
        Log.i("MineFragment", "MineFragment 文件写入成功");
    }
}
